/**
 * 不需要身份验证即可以使用的路由
 * @type {createApplication}
 */
const express = require('express');
const bodyParser = require('body-parser');

const roodCategoryMid = require('../middleware/rootCategoryMid');
const userMid = require('../middleware/userMid');
const goodsMid = require('../middleware/goodsMid');
const uploadMid = require('../middleware/uploadMid');

const utils = require('../common/utils');

const noVerApp = express();

/**配置post*/
noVerApp.use(bodyParser.urlencoded({ extended: false }));//解析post请求数据
noVerApp.use(bodyParser.json());//数据JSON类型
/**配置post*/

/**获取首页的相关信息*/
noVerApp.post('/index', [roodCategoryMid.gRootCategory, uploadMid.gIndexSwiperList], (request, response) => {
  let {root_navs, index_swiper_all} = request;
  let result = {
    data: {
      root_navs, // root类目
      index_swiper_all, // 首页轮播图列表
    }
  };
  return response.status(200).send(result);
})


/**
 * 用户登录提交后的动作处理     判断是否登录成功
 */
noVerApp.post('/login' , [userMid.gUserByUnameAndPwd] , (request , response , next) => {
  let { user } = request;//从中间件userMid方法中获取user
  if(user) {   //如果user不为空，即登录成功

    /**创建令牌token*/
    const token = utils.setToken(user.username, user.business);
    console.log('token生成成功:' + token);console.log();console.log();console.log();
    let data = {
      code: 200,
      'msg': '登陆成功',
      token,
    };
    response.status(200).send(data);
  } else {    //否则，即登录不成功
    let data = {
      code: 401,
      'msg': '登陆失败',
    };
    response.status(200).send(data);
  }
})

/**
 * 用户注册
 */
noVerApp.post('/register', [userMid.sUser], (request, response, next) => {
  if (request.add_uid) { // 添加用户成功
    console.log(request.user.username + '用户添加成功');
    let meta = {
      code: 200,
      'msg': '注册成功'
    };
    response.status(200).send(meta);
  } else { // 添加用户失败
    let meta = {
      code: 201,
      'msg': '注册失败!!!'
    };
    response.status(200).send(meta);
  }
})



module.exports = noVerApp;

